const express = require('express')
const md5 = require('md5')
const router = express.Router()
const db = require('../db/index')
//导入token
// const jwt=require('jsonwebtoken')
// const config=require('../config')
const Token = require('../router_handler/token')
const verify = require('../router_handler/verify')
//信息提示
const Constant = require('../router/error/constant');

//注册
router.post('/register', verify.verifyToken, (req, res) => {
    let userinfo = req.body
    if (!userinfo.username || !userinfo.password) {
        res.send({
            status: 403,
            message: '用户名或密码不合法!'
        })
    }
    let sqlstr = 'select * from user where username=?'
    db.query(sqlstr, userinfo.username, (err, results) => {
        if (err) {
            return res.send({
                status: 403,
                message: err.message
            })
        }
        if (results.length > 0) {
            return res.send({
                status: 403,
                message: '用户名被占用，请重新注册'
            })
        }
            //md5加密
    userinfo.password = md5(userinfo.password)

    sqlstr = 'insert into user set ?'
    db.query(sqlstr, {
        username: userinfo.username,
        password: userinfo.password,
        role: userinfo.role,
        is_del:0
    }, (err, results) => {
        if (err) {
            return res.send({
                status: 403,
                message: err.message
            })
        }

        if (results.affectedRows !== 1) {
            return res.send({
                status: 403,
                message: '注册失败，请稍后重试'
            })
        }
        res.send({
            status: 201,
            message: '注册成功！'
        })
    })
    })


})
//登录
router.post('/login',(req, res) => {
    let userinfo = req.body
    if (!userinfo.username || !userinfo.password) {
        // res.send({status:403,message:'用户名或密码不合法!'})
        res.cc('用户名或密码不合法!')
    }
    let sqlstr = 'select * from user where username=?'
    db.query(sqlstr, userinfo.username, async (err, results) => {
        if (err) {
            return res.cc(err)
        }
        if (results.length == 0) {
            res.cc('该用户未注册')
        }
        // res.cc(results,201)
        if (md5(userinfo.password) !== results[0].password) {
            res.cc('密码错误，登陆失败')
        }
        sqlstr = 'select * from role where rid="'+results[0].role+'"'
        let results2 = await db.promise().query(sqlstr)
        let role_arr = results2[0][0].powerid.split(",")
        if(role_arr.powerid!=[]){
            sqlstr = 'select * from power where '
            role_arr.forEach((item,index)=>{
                sqlstr += 'pid=' + item + ' or '
            })
            sqlstr = sqlstr.substring(0, sqlstr.length - 4)
        } else {
            // 如果权限为空
             results[0].power=[]
             const user = {
                ...results[0],
                password: ''
            }
             return res.send({
                status: 201,
                message: "登陆成功",
                data: {
                    username: user,
                    token: Token.encrypt(user)
                }
            })
        }
        const results3 = await db.promise().query(sqlstr)
        results[0].power=results3[0]
        const user = {
            ...results[0],
            password: ''
        }
        
        //加密用户信息生成token
        res.send({
            status: 201,
            message: "登陆成功",
            data: {
                username: user,
                token: Token.encrypt(user)
            }
        })
    })
})


//获取权限列表
router.get('/getpower', verify.verifyToken, (req, res) => {
    let sqlstr = 'select * from power'
    db.query(sqlstr, (err, results) => {
        if (err) {
            return res.send({
                status: 403,
                message: err.message
            })
        }
        if (results.length == 0) {
            return res.send(Constant.DATA_NULL)
        }
        //保存查询数据
        let data = results
        res.send({
            data,
            ...Constant.DATA_SUCCESS
        })
        // sqlstr='select * from toppower'
        // db.query(sqlstr,(err,results)=>{
        //     if(err){
        //         return res.send({status:403,message:err.message})
        //     }
        //     // 添加树形结构
        //     results.forEach(res=>{
        //         res.child=[]
        //     })
        //     // res.send({results,...Constant.DATA_SUCCESS})
        //     //给树形结构添加数据
        //     data.forEach(ele => {
        //         results.forEach(res=>{
        //             if(ele.toppid==res.toppid){
        //                 ele.toppid=ele.pid+50
        //                 res.child.push(ele)
        //             }
        //         })

        //     });
        //     // 输出最后数据
        //     res.send({data:results,...Constant.DATA_SUCCESS})

        // })
    })
})
//添加权限
router.post('/addpower', verify.verifyToken, (req, res) => {
    let data = req.body
    let sqlstr = 'INSERT INTO power (power,pname) values("' + data.power + '","' + data.pname + '")'
    db.query(sqlstr, (err, results) => {
        if (err) {
            return res.send({
                status: 403,
                message: err.message
            })
        }
        if (results.affectedRows !== 1) {
            return res.send({
                status: 403,
                message: '添加失败,请稍后再试'
            })
        }
        res.send({
            status: 201,
            message: '添加成功'
        })

    })
})
//修改权限
router.post('/editpower', verify.verifyToken, (req, res) => {
    let data = req.body
    if (data.pid < 4) {
        return res.send({
            status: 403,
            message: '修改失败,系统设置不可操作'
        })
    }
    let sqlstr = 'UPDATE power SET power="' + data.power + '",pname="' + data.pname + '"where pid="' + data.pid + '"'
    db.query(sqlstr, (err, results) => {
        if (err) {
            return res.send({
                status: 403,
                message: err.message
            })
        }
        if (results.affectedRows !== 1) {
            return res.send({
                status: 403,
                message: '修改失败,请稍后再试'
            })
        }
        res.send({
            status: 201,
            message: '修改成功'
        })

    })
})
//删除权限
router.post('/delpower', verify.verifyToken, (req, res) => {
    let data = req.body
    if (data.pid < 4) {
        return res.send({
            status: 403,
            message: '删除失败,系统设置不可操作'
        })
    }
    let sqlstr = 'DELETE FROM power where pid="' + data.pid + '"'
    db.query(sqlstr, (err, results) => {
        if (err) {
            return res.send({
                status: 403,
                message: err.message
            })
        }
        if (results.affectedRows !== 1) {
            return res.send({
                status: 403,
                message: '删除失败,请稍后再试'
            })
        }
        res.send({
            status: 201,
            message: '删除成功'
        })

    })
})


//获取角色列表
router.get('/getrole', verify.verifyToken, async (req, res) => {
    // async function selsql(str){

    //     return rows
    //  }
    let sqlstr = 'select * from role'
    const [data] = await db.promise().query(sqlstr)
    if (data.length == 0) {
        return res.send(Constant.DATA_NULL)
    }
    data.forEach(async (item, index) => {
        let item_arr = item.powerid.split(",")
        if (item_arr.powerid != []) {
            sqlstr = 'select * from power where '
            item_arr.forEach(ele => {
                sqlstr += 'pid=' + ele + ' or '

            });
            sqlstr = sqlstr.substring(0, sqlstr.length - 4)
        } else {
            // 如果权限为空
            let data = {}
        }
        const [data2] = await db.promise().query(sqlstr)
        data[index].role = data2
        if (index == data.length - 1) {
            res.send({
                data,
                ...Constant.DATA_SUCCESS
            })
        }
    })
})
//添加角色
router.post('/addrole', verify.verifyToken, (req, res) => {
    let data = req.body
    if (data.powerid==undefined) {
        return res.send({
            status: 403,
            message: '添加失败,必须含有一个权限'
        })
    }
    data.powerid = data.powerid.join(",")
    let sqlstr = 'INSERT INTO role (rolename,powerid) values("' + data.rolename + '","' + data.powerid + '")'
    console.log(sqlstr);
    db.query(sqlstr, (err, results) => {
        if (err) {
            console.log(err);
            return res.send({

                status: 403,
                message: err.message
            })
        }
        if (results.affectedRows !== 1) {
            return res.send({
                status: 403,
                message: '添加失败,请稍后再试'
            })
        }
        res.send({
            status: 201,
            message: '添加成功'
        })

    })
})
//修改角色
router.post('/editrole', verify.verifyToken, (req, res) => {
    let data = req.body
    if (data.powerid==undefined) {
        return res.send({
            status: 403,
            message: '修改失败,必须含有一个权限'
        })
    }
    let sqlstr = 'UPDATE role SET powerid="' + data.powerid + '",rolename="' + data.rolename + '"where rid="' + data.rid + '"'
    db.query(sqlstr, (err, results) => {
        if (err) {
            return res.send({
                status: 403,
                message: err.message
            })
        }
        if (results.affectedRows !== 1) {
            return res.send({
                status: 403,
                message: '修改失败,请稍后再试'
            })
        }
        res.send({
            status: 201,
            message: '修改成功'
        })

    })
})
//删除角色
router.post('/delrole', verify.verifyToken, (req, res) => {
    let data = req.body
    let sqlstr = 'DELETE FROM role where rid="' + data.rid + '"'
    db.query(sqlstr, (err, results) => {
        if (err) {
            return res.send({
                status: 403,
                message: err.message
            })
        }
        if (results.affectedRows !== 1) {
            return res.send({
                status: 403,
                message: '删除失败,请稍后再试'
            })
        }
        res.send({
            status: 201,
            message: '删除成功'
        })

    })
})

//获取管理员列表
router.get('/getadmin', verify.verifyToken, async (req, res) => {
    // async function selsql(str){

    //     return rows
    //  }
    let sqlstr = 'select uid,username,role from user where is_del=0'
    const [data] = await db.promise().query(sqlstr)
    if (data.length == 0) {
        return res.send(Constant.DATA_NULL)
    }
    data.forEach(async (item, index) => {
        sqlstr = 'select * from role where rid='+item.role
        // let item_arr = item.powerid.split(",")
        // if (item_arr.powerid != []) {
        //     sqlstr = 'select * from power where '
        //     item_arr.forEach(ele => {
        //         sqlstr += 'pid=' + ele + ' or '

        //     });
        //     sqlstr = sqlstr.substring(0, sqlstr.length - 4)
        // } else {
        //     // 如果权限为空
        //     let data = {}
        // }
        const [data2] = await db.promise().query(sqlstr)
        data[index].role = data2[0]
        if (index == data.length - 1) {
            res.send({
                data,
                ...Constant.DATA_SUCCESS
            })
        }
    })
})
//修改管理员
router.post('/editadmin', verify.verifyToken, (req, res) => {
    let data = req.body
    let sqlstr =''
    if (data.password==undefined) {
     sqlstr = 'UPDATE user SET role="' + data.role + '"where uid="' + data.uid + '"'
        
    }else{
        data.password = md5(data.password)
     sqlstr = 'UPDATE user SET role="' + data.role + '",password="' + data.password + '"where uid="' + data.uid + '"'

    }
    console.log(data);
    // let sqlstr = 'UPDATE role SET powerid="' + data.powerid + '",rolename="' + data.rolename + '"where rid="' + data.rid + '"'
    db.query(sqlstr, (err, results) => {
        if (err) {
            return res.send({
                status: 403,
                message: err.message
            })
        }
        if (results.affectedRows !== 1) {
            return res.send({
                status: 403,
                message: '修改失败,请稍后再试'
            })
        }
        res.send({
            status: 201,
            message: '修改成功'
        })

    })
})
//删除管理员
router.post('/deladmin', verify.verifyToken, (req, res) => {
    let data = req.body
    let sqlstr = 'UPDATE user SET is_del="' + data.del + '"where uid="' + data.uid + '"'
    db.query(sqlstr, (err, results) => {
        if (err) {
            return res.send({
                status: 403,
                message: err.message
            })
        }
        if (results.affectedRows !== 1) {
            return res.send({
                status: 403,
                message: '删除失败,请稍后再试'
            })
        }
        res.send({
            status: 201,
            message: '删除成功'
        })

    })
})
module.exports = router